package com.tjetc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tjetc.common.JsonResult;
import com.tjetc.common.JwtTokenUtil;
import com.tjetc.dao.AdminMapper;
import com.tjetc.dao.EmployeeMapper;
import com.tjetc.dao.PostInfoMapper;
import com.tjetc.entity.Admin;
import com.tjetc.entity.Employee;
import com.tjetc.entity.PostInfo;
import com.tjetc.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class AdminServiceImpl implements AdminService {
    @Value("${token.expiration}")
    private int tokeExpiraton;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public JsonResult findById(Long id) {
        //selectById是mybatisplus提供的单表查询操作，生成sql语句都是mybatisplus内置
        Admin admin=adminMapper.selectById(id);
        Employee employee=employeeMapper.selectById(adminMapper.selectEmpolyeeId(id));
        admin.setEmployee(employee);
        return JsonResult.success(admin);
    }
    @Override
    public JsonResult login(String username, String password){
        //如果任何一个为空，都返回true
    if (StringUtils.isAnyBlank(username,password)){
        return JsonResult.fail("用户名或者密码不能为空");
    }
    //根据用户名和密码查询Admin
        Admin admin=adminMapper.selectByUsernameAndPassword(username,password);
    if (admin==null){
        return JsonResult.fail("用户名或者密码错误");
    }else {
        //用户名或者密码正确,生成token
        Map<String,Object> claims=new HashMap<>();
        claims.put("adminId",admin.getAdminId());
        String token=JwtTokenUtil.generateToken(claims,"admin",tokeExpiraton);
        return JsonResult.success(token,admin);
    }
    }

    @Override
    public JsonResult findPage(String username, Integer pageNo, Integer pageSize) {
        //设置页码和每页数量
        Page<Admin> page=Page.of(pageNo,pageSize);
        //把adminPage传入mapper查询中，adminPage就是最后的分页结果
        Page<Admin>adminPage= adminMapper.selectPageLikeUsername(page,username);
        // 遍历结果，为每个Admin设置Employee
        for (Admin admin : adminPage.getRecords()) {
            Employee employee = employeeMapper.selectById(adminMapper.selectEmpolyeeId(admin.getAdminId()));
            admin.setEmployee(employee);
        }
        //convert方法转换Page中 records集合元素类型 Admin---->AdminView
        //new Function<Admin,AdminView>(){};表示创建一个实现Function的匿名类 对象
        return JsonResult.success(adminPage);
    }
    @Override
    public JsonResult deleteById(Long id) {
        int rows=adminMapper.deleteById(id);
        if (rows>0){
            return JsonResult.success("删除成功");
        }
        else {
            return JsonResult.fail("删除失败");
        }
    }
    //@Transactional用在service方法上，保证事务
    //注意：默认情况@Transactional只对运行时异常起作用(RuntimeException)
    @Transactional
    @Override
    public JsonResult save(Admin adminParam) {
        Admin admin=null;
        LocalDateTime now=LocalDateTime.now();
        //通过判断id值有无判断是新增还是更新，id值无是新增，id值有就是更新
        if(adminParam.getAdminId()==null||adminParam.getAdminId()<=0){
            //新增
            //判断用户名或者密码不为空
            if(StringUtils.isAnyBlank(adminParam.getUsername(),adminParam.getPassword())){
                return JsonResult.fail("新增用户名，用户名和密码不能为空");
            }
            //判断用户名不能重复
            Admin exiseAdmin=adminMapper.selectByUsername(adminParam.getUsername());
            if(exiseAdmin!=null){
                return JsonResult.fail("用户名已经存在");
            }
            //新增
            admin=new Admin();
            BeanUtils.copyProperties(adminParam,admin);
            admin.setCreateTime(now);
            admin.setUpdateTime(now);
            adminMapper.insert(admin);
            return JsonResult.success("新增成功",null);
        }else{
            //更新
            //根据id查询Admin信息
            admin=adminMapper.selectById(adminParam.getAdminId());
            if(admin==null){
            return JsonResult.fail("用户不存在，更新失败");
            }
            //要更新的字段
            admin.setUsername(adminParam.getUsername());
            admin.setEmployeeId(adminParam.getEmployeeId());
            admin.setEmployee(adminParam.getEmployee());
            admin.setPassword(adminParam.getPassword());
            admin.setUpdateTime(now);
            int rows=adminMapper.updateById(admin);
            if (rows>0){
                return JsonResult.success("更新成功",null);
            }else {
                return JsonResult.fail("用户不存在，更新失败");
            }
        }
    }
}
